package com.xpqh.ksg.modular.overseas.service;

import com.xpqh.ksg.common.persistence.dao.KsgBrandInfoMapper;
import com.xpqh.ksg.common.persistence.dao.KsgCaseInfoMapper;
import com.xpqh.ksg.common.persistence.model.*;
import com.xpqh.ksg.modular.auth.dto.KsgVerificationRespDTO;
import com.xpqh.ksg.modular.core.dto.*;
import com.xpqh.ksg.modular.overseas.dto.*;
import com.xpqh.ksg.modular.overseas.dto.KsgOverseasCarColor;
import com.xpqh.ksg.modular.overseas.dto.KsgStoreInfoListRespDTO;
import com.xpqh.ksg.modular.warranty.dto.KsgProductNameListRespDTO;
import com.xpqh.ksg.modular.warranty.dto.WarrantyInfoRespDTO;
import common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class IKsgService {

    @Autowired
    private KsgCaseInfoMapper caseInfoMapper;

    public List<KsgOverseasBanner> getOverseasBannerList() {
        return caseInfoMapper.getOverseasBannerList();
    }
    public List<KsgOverseasCaseBlog> getCaseBlogList(String type, Integer pageNo, Integer pageSize) {
        return caseInfoMapper.getCaseBlogList(type,(pageNo - 1) * pageSize, pageSize);
    }

    public Integer getCaseBlogListCount(String type) {
        return caseInfoMapper.getCaseBlogListCount(type);
    }
    public KsgOverseasCaseInfoRespDTO getOverseasCaseInfoCaseInfo(String caseId) {
        KsgOverseasCaseInfoRespDTO respDTO = new KsgOverseasCaseInfoRespDTO();
        respDTO.setCaseBlogInfo( caseInfoMapper.getOverseasCaseInfoCaseInfo(caseId));
        respDTO.setLastCaseBlogInfo(caseInfoMapper.getOverseasLastCaseInfoCaseInfo(caseId,respDTO.getCaseBlogInfo().getType()));
        respDTO.setNextCaseBlogInfo(caseInfoMapper.getNextOverseasCaseInfoCaseInfo(caseId,respDTO.getCaseBlogInfo().getType()));
        return respDTO;
    }

    public List<KsgOverseasColorOptionRespDTO> getOverseasColorOption() {
        List<KsgOverseasColorOptionRespDTO> overseasColorOption = caseInfoMapper.getOverseasColorOption();
        List<KsgOverseasCarColor> carColorList = caseInfoMapper.getCarColorList();
        for (KsgOverseasColorOptionRespDTO ksgOverseasColorOptionRespDTO : overseasColorOption) {
            List<KsgOverseasCarColor> list = new ArrayList<>();
            for (KsgOverseasCarColor ksgOverseasCarColor : carColorList) {
                if (ksgOverseasColorOptionRespDTO.getId().equals(ksgOverseasCarColor.getCarId())) {
                    list.add(ksgOverseasCarColor);
                }
            }
            ksgOverseasColorOptionRespDTO.setCarColorList(list);
        }
        return overseasColorOption;
    }

    public Integer getIpCount(String ip, Integer type) {
        if (type == 0) {
            return caseInfoMapper.getIpCountOne(ip);
        }else {
            return caseInfoMapper.getIpCountTwo(ip);
        }
    }


    public Integer overseasContactUs(KsgOverseasContactUsReqDTO reqDTO) {
//        //1.创建Session
//        try {
//            Session session= JavaMailUtils.createSession();
//            System.out.println(session);
//
//            //2.创建邮件对象
//            MimeMessage message=new MimeMessage(session);
//            //设置邮件主题
//            message.setSubject("官网联系我们信息提交");
//            //设置邮件内容
//            message.setText("Which best describes you? : "+reqDTO.getDescribes()+"\r\n" +
//                    "Country:"+reqDTO.getCountry()+"\r\n" +
//                    "First Name:"+reqDTO.getFirstName()+"\r\n" +
//                    "Last Name:"+reqDTO.getLastName()+"\r\n" +
//                    "Company:"+reqDTO.getCompany()+"\r\n" +
//                    "Phone Number / Whatsapp:"+reqDTO.getPhoneOrWhatsapp()+"\r\n" +
//                    "Email:"+reqDTO.getEmail()+"\r\n" +
//                    "Area of Interest :"+reqDTO.getInterest()+"\r\n" +
//                    "Questions / Comments:"+reqDTO.getQuestionsOrComments()+"");
//            //设置发件人
//            message.setFrom(new InternetAddress("18202767858@163.com"));
//            //设置收件人
//            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("KSGPPF01@gmail.com"));
//
//            //3.发送邮件
//            Transport.send(message);
//        } catch (AddressException e) {
//            e.printStackTrace();
//        } catch (MessagingException e) {
//            e.printStackTrace();
//        }
        return caseInfoMapper.overseasContactUs(reqDTO.getDescribes(),reqDTO.getCountry(),reqDTO.getFirstName(),reqDTO.getLastName(),reqDTO.getCompany(),reqDTO.getPhoneOrWhatsapp(),reqDTO.getEmail(),reqDTO.getQuestionsOrComments(),reqDTO.getInterest(),reqDTO.getIp(),reqDTO.getType());

    }
    public KsgOverseasHomeRespDTO getOverseasHome() {
        KsgOverseasHomeRespDTO respDTO = new KsgOverseasHomeRespDTO();
        respDTO.setBannerList(caseInfoMapper.getOverseasBannerList());
        respDTO.setProductList(caseInfoMapper.getOverseasProductList());
        respDTO.setCaseBlogList(caseInfoMapper.getOverseasCaseBlogList());
        return respDTO;
    }

    public Integer overseasInfoSubmit(KsgOverseasInfoSubmitReqDTO reqDTO) {
        return caseInfoMapper.overseasInfoSubmit(reqDTO.getInformation(),reqDTO.getName(),reqDTO.getCountry(),reqDTO.getEmail(),reqDTO.getIp());
    }

    public List<KsgOverseasProduct> getProductInfo(String productType) {
        return caseInfoMapper.getProductInfo(productType);
    }

    public List<KsgOverseasQuestionsRespDTO> getOverseasQuestions() {
        return caseInfoMapper.getOverseasQuestions();
    }
    public Integer insertPopUpUser(String phone, String name, String carModel,Integer type) {
        return caseInfoMapper.insertPopUpUser(phone, name, carModel,type);
    }
    public Object getProductNameList(Integer type,Integer channelType,Integer productType) {
        if (type == 1) {
            return caseInfoMapper.getProductNameListAll();
        }
        if (null == channelType) {
            return caseInfoMapper.getProductNameList();
        }else {
            List<KsgProductListRespDTO> productList = caseInfoMapper.getProductList(productType,channelType);
            for (KsgProductListRespDTO respDTO : productList) {
                respDTO.setProductList(caseInfoMapper.getProductNameListByChannel(respDTO.getSeriesName(),channelType,productType));
            }
            return productList;
        }
    }

    public List<KsgProductSeriesListRespDTO> getProductSeriesList(Integer productId) {
        return caseInfoMapper.getProductSeriesList(productId);
    }

    public List<KsgNewsListRespDTO> searchByPc(Integer pageNo, Integer pageSize, String search) {
        List<KsgNewsListRespDTO> list = caseInfoMapper.searchByPc((pageNo - 1) * pageSize, pageSize,search);
        if (null != list) {
            for (KsgNewsListRespDTO ksgNewsListRespDTO : list) {
                ksgNewsListRespDTO.setCover(ksgNewsListRespDTO.getCover() + "?x-oss-process=style/watermark");
            }
        }
        return list;
    }

    public Integer searchByPcCount(String search) {
        return caseInfoMapper.searchByPcCount(search);
    }
    public List<KsgSeriesInfo> getSeriesList(String brandId) {
        return caseInfoMapper.getSeriesList(brandId);
    }

    public List<KsgStoreInfoListRespDTO> getStoreInfoList(Integer pageNo,Integer pageSize,String address) {
        return caseInfoMapper.getStoreInfoList2((pageNo - 1) * pageSize, pageSize,address);
    }
    public WarrantyInfoRespDTO getWarrantyInfo(String phone) {
        WarrantyInfoRespDTO warrList = new WarrantyInfoRespDTO();
        if (phone.startsWith("PPF")) {
            phone = phone.replace("PPF","");
        }
        warrList = caseInfoMapper.getWarrList(phone);
        if (null != warrList) {
            if (null != warrList.getConstructionDate() && warrList.getConstructionDate().length() > 10) {
                warrList.setConstructionDate(warrList.getConstructionDate().substring(0, 10));
            }
            String signalId = warrList.getSignalId();
            String[] split = signalId.split("-");
            KsgProductNameListRespDTO productBySeriesId = caseInfoMapper.getProductBySeriesId(split[0]);
            if (productBySeriesId != null) {
                warrList.setProductName(productBySeriesId.getProductName());
                warrList.setProductBatch(split[1]);
                warrList.setProductBox(split[2]);
                warrList.setBatch(split[1]);
                warrList.setBox(split[2]);
            }
            warrList.setCarMembraneList(caseInfoMapper.getCarMembraneList(warrList.getWarrantyNumber()));
            Date createTime = warrList.getCreateTime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(createTime);
            calendar.add(Calendar.YEAR,productBySeriesId.getTerm());
            Date time = calendar.getTime();
            warrList.setEndTime(productBySeriesId.getTerm() + "年");
            String time1 = getTime(time, new Date());
            warrList.setTerm(time1);
            return warrList;
        }else {
            return null;
        }
    }


    public List<WarrantyInfoRespDTO> getWarrantyList(String phone) {
        if (phone.startsWith("PPF")) {
            phone = phone.replace("PPF","");
        }
        List<WarrantyInfoRespDTO> warrList2 = caseInfoMapper.getWarrList2(phone);
        for (WarrantyInfoRespDTO warrList : warrList2) {
            if (null != warrList.getConstructionDate() && warrList.getConstructionDate().length() > 10) {
                warrList.setConstructionDate(warrList.getConstructionDate().substring(0, 10));
            }
            String signalId = warrList.getSignalId();
            String[] split = signalId.split("-");
            KsgProductNameListRespDTO productBySeriesId = caseInfoMapper.getProductBySeriesId(split[0]);
            if (productBySeriesId != null) {
                warrList.setProductName(productBySeriesId.getProductName());
                warrList.setProductBatch(split[1]);
                warrList.setProductBox(split[2]);
                warrList.setBatch(split[1]);
                warrList.setBox(split[2]);
                warrList.setEndTime(productBySeriesId.getTerm() + "年");
                Date createTime = warrList.getCreateTime();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(createTime);
                calendar.add(Calendar.YEAR,productBySeriesId.getTerm());
                Date time = calendar.getTime();

                String time1 = getTime(time, new Date());
                warrList.setTerm(time1);
            }
            warrList.setCarMembraneList(caseInfoMapper.getCarMembraneList(warrList.getWarrantyNumber()));

        }
        return warrList2;
    }


    public static String getTime(Date currentTime,Date firstTime){
        long diff = currentTime.getTime() - firstTime.getTime();//这样得到的差值是微秒级别
        Calendar  currentTimes =dataToCalendar(currentTime);//当前系统时间转Calendar类型
        Calendar  firstTimes =dataToCalendar(firstTime);//查询的数据时间转Calendar类型
        int year = currentTimes.get(Calendar.YEAR) - firstTimes.get(Calendar.YEAR);//获取年
        int month = currentTimes.get(Calendar.MONTH) - firstTimes.get(Calendar.MONTH);
        int day = currentTimes.get(Calendar.DAY_OF_MONTH) - firstTimes.get(Calendar.DAY_OF_MONTH);
        if (day < 0) {
            month -= 1;
            currentTimes.add(Calendar.MONTH, -1);
            day = day + currentTimes.getActualMaximum(Calendar.DAY_OF_MONTH);//获取日
        }
        if (month < 0) {
            month = (month + 12) % 12;//获取月
            year--;
        }
        long days = diff / (1000 * 60 * 60 * 24);
        long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60); //获取时
        long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);  //获取分钟
        long s=(diff/1000-days*24*60*60-hours*60*60-minutes*60);//获取秒
        String CountTime=""+year+"年"+month+"月"+day+"天"+hours+":"+minutes;
        return CountTime;
    }
    public static Calendar dataToCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }
    public List<KsgNewsListRespDTO> getNewsList(Integer pageNo, Integer pageSize,String searchContent) {
        List<KsgNewsListRespDTO> list = caseInfoMapper.getNewsList((pageNo - 1) * pageSize, pageSize,searchContent);
        if (null != list) {
            for (KsgNewsListRespDTO ksgNewsListRespDTO : list) {
                ksgNewsListRespDTO.setCover(ksgNewsListRespDTO.getCover() + "?x-oss-process=style/watermark");
            }
        }
        return list;
    }

    public Integer getNewsCount(String  searchContent) {
        return caseInfoMapper.getNewsListCount(searchContent);
    }

    public List<KsgDistributorBatchRespDTO> getDistributorBatch(Integer userid, Integer userLevel) {
        KsgStoreInfo storeInfo = caseInfoMapper.getStoreInfo(userid);
        userLevel = storeInfo.getUserLevel();
        return caseInfoMapper.getDistributorBatch(storeInfo.getUserCode(), userLevel);
    }

    public List<KsgDistributorStoreRespDTO> getDistributorStore(Integer userid, Integer userLevel) {
        KsgStoreInfo storeInfo = caseInfoMapper.getStoreInfo(userid);
        userLevel = storeInfo.getUserLevel();
        return caseInfoMapper.getDistributorStore(storeInfo.getUserCode(), userLevel);
    }

    public List<KsgStockListRespDTO> getStockList(KsgStockListReqDTO reqDTO) {
        String batchNum = "";
        String boxNum = "";

        KsgStoreInfo storeInfo = caseInfoMapper.getStoreInfo(reqDTO.getUserId());
            String userLevel  = storeInfo.getUserLevel() + "";
        if (StringUtils.isNotBlank(userLevel)) {
            reqDTO.setUserLevel(Integer.valueOf(userLevel));
        }
        if (StringUtils.isNotBlank(reqDTO.getSearch())) {
            reqDTO.setSearch(reqDTO.getSearch().toUpperCase());
        }

        List<KsgStockListRespDTO> stockList = caseInfoMapper.getStockList(reqDTO.getType(), storeInfo.getUserCode(), reqDTO.getUserLevel(), reqDTO.getProductName(), reqDTO.getProductSeries(), batchNum, reqDTO.getStoreId(), boxNum, reqDTO.getSearch(), (reqDTO.getPageNo() - 1) * reqDTO.getPageSize(), reqDTO.getPageSize());
        stockList.forEach(sjStockInfo -> {
            sjStockInfo.setXsxx(sjStockInfo.getProductName()+"/"+
                    sjStockInfo.getWindowType()+"/"+
                    sjStockInfo.getSignalId()
            );

        });
        return stockList;
    }

    public List<KsgStockListRespDTO> getStockListByUserId(KsgStockListReqDTO reqDTO) {

        KsgStoreInfo storeInfo = caseInfoMapper.getStoreInfo(reqDTO.getUserId());
        if ( storeInfo == null || null == storeInfo.getUserCode()) {
            return new ArrayList<>();
        }
        if (StringUtils.isNotBlank(reqDTO.getSearch())) {
            reqDTO.setSearch(reqDTO.getSearch().toUpperCase());
        }
        List<KsgStockListRespDTO> stockList = caseInfoMapper.getStockListByUserCode(storeInfo.getUserCode(), reqDTO.getSearch());
        stockList.forEach(sjStockInfo -> {
            sjStockInfo.setXsxx(sjStockInfo.getProductName()+"/"+
                    sjStockInfo.getWindowType()+"/"+
                    sjStockInfo.getSignalId()
            );

        });
        return stockList;
    }



}
